<template>
  <el-card style="height: 100%; ">
    <el-container style="height: 100%; display: flex; flex-direction: column;">
      <el-header>
        <el-form inline>
          <el-form-item  style="width: 20%">
            <el-input v-model="keyWord" placeholder="卡密"></el-input>
          </el-form-item>
          <el-form-item style="width: 15%" >
            <el-select v-model="type" placeholder="请选择类型">
              <el-option label="全选" value=""></el-option>
              <el-option label="注册" value="ZC"></el-option>
              <el-option label="激活" value="JH"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="width: 15%">
            <el-select v-model="sell" placeholder="请选择售出">
              <el-option label="全选" value=""></el-option>
              <el-option label="未售出" value="true"></el-option>
              <el-option label="已售出" value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  style="width: 15%">
            <el-select v-model="usable" placeholder="请选择使用">
              <el-option label="全选" value=""></el-option>
              <el-option label="未使用" value="true"></el-option>
              <el-option label="已使用" value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="width: 20%">
            <el-button type="primary" @click="getKeys" style="width: 100%">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
           height="calc(100vh - 60px - 40px - 50px - 20px - 20px - 20px - 20px)">
          <el-table-column
              align="center"
              prop="id"
              label="id"
              width="50">
          </el-table-column>
          <el-table-column
              align="center"
              prop="keyWord"
              label="卡密"
              width="150">
          </el-table-column>
          <el-table-column
              align="center"
              prop="type"
              label="类型"
              width="60">
          </el-table-column>
          <el-table-column
              align="center"
              prop="addTime"
              label="添加时间"
              width="160">
            <template #default="{ row }">
              {{ formatDate(row.addTime) }}
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              width="160"
              prop="addOperator"
              label="添加人">
          </el-table-column>
          <el-table-column
              prop="sell"
              label="售卖">
            <template #default="{ row }">
              <span v-if="row.sell===true" style="color: green">未售出</span>
              <span v-else-if="row.sell===false && row.usable===false" style="color: red">已售出</span>
              <span v-else-if="row.sell===false && row.usable===true" style="color: blue">已售出</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="seller"
              label="售卖人">
          </el-table-column>
          <el-table-column
              prop="sellingTime"
              label="售卖时间">
            <template #default="{ row }">
              {{ formatDate(row.sellingTime) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="usable"
              label="使用">
            <template #default="{ row }">
              <span v-if="row.usable===true && row.usable===true" style="color: green">未使用</span>
              <span v-if="row.usable===false && row.usable===true" style="color: blue">未使用</span>
              <span v-else-if="row.usable===false" style="color: red">已使用</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="username"
              label="使用人">
          </el-table-column>
          <el-table-column
              prop="usageTime"
              label="使用时间">
            <template #default="{ row }">
              {{ formatDate(row.usageTime) }}
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              prop="action"
              label="操作"
              width="100"
              align="center">
            <template #default="{ row }">
              <el-link icon="el-icon-chat-line-round" :underline="false" v-if="row.sell" type="success"
                       @click="sellKey(row)">
                出售
              </el-link>

              <el-link icon="el-icon-chat-round" :underline="false" v-else type="danger" disabled>
                售出
              </el-link>
            </template>

          </el-table-column>

        </el-table>
      </el-main>
      <el-footer>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            @next-click="handleNextClick"
            @prev-click="handlePrevClick"
            background
            :current-page="page"
            layout="sizes, prev, pager, next,jumper,total"
            :page-size="10"
            :page-sizes="[10,20,50,100]"
            :total="total">

        </el-pagination>
      </el-footer>
    </el-container>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import apiClient from '@/utils/axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { dateFormat } from '@/utils/DateFormat'

interface KeyRow {
  id: number
  keyWord: string
  type: string
  addTime: string | null
  addOperator: string
  sell: boolean
  seller: string | null
  sellingTime: string | null
  usable: boolean
  username: string | null
  usageTime: string | null
}

const page = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)

const keyWord = ref<string>('')
const type = ref<string>('ZC')
const sell = ref<string | boolean>('')
const usable = ref<string | boolean | null>(null)

const tableData = ref<KeyRow[]>([])

const router = useRouter()

const formatDate = (val: string | null) => {
  if (!val) return ''
  return dateFormat(val, 'YYYY-MM-DD HH:mm:ss')
}

const getKeys = () => {
  apiClient
    .get('/admin/query_keys', {
      params: {
        page: page.value,
        pageSize: pageSize.value,
        keyWord: keyWord.value,
        type: type.value,
        sell: sell.value,
        usable: usable.value,
      },
    })
    .then((res) => {
      if (res.data.status === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          placement: 'top-right',
        })
        tableData.value = res.data.data.rows
        total.value = res.data.data.total
      } else
        ElMessage({
          message: res.data.msg,
          type: 'error',
          placement: 'top-right',
        })
    })
}

const sellKey = (row: KeyRow) => {
  if (!localStorage.getItem('a')) {
    ElMessage({
      message: '未登录',
      type: 'error',
      placement: 'top-right',
    })
    router.push('/login')
    return
  }

  ElMessageBox.confirm(`将出售该卡密: ${row.keyWord}，是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      apiClient
        .get('/admin/sell_keys', {
          params: {
            id: row.id,
            keyWord: row.keyWord,
            seller: localStorage.getItem('a'),
          },
        })
        .then((res) => {
          if (res.data.status === 200) {
            const textArea = document.createElement('textarea')
            textArea.value = row.keyWord
            document.body.appendChild(textArea)
            textArea.select()
            document.execCommand('copy')
            document.body.removeChild(textArea)
            ElMessage({
              message: '卡密已复制到剪切板!',
              type: 'success',
              placement: 'top-right',
            })
            ElMessage({
              message: res.data.msg,
              type: 'success',
              placement: 'top-right',
            })
            getKeys()
          } else
            ElMessage({
              message: res.data.msg,
              type: 'error',
              placement: 'top-right',
            })
        })
    })
    .catch(() => {
      ElMessage({
        message: '已取消出售',
        type: 'info',
        placement: 'top-right',
      })
    })
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  getKeys()
}

const handleCurrentChange = (val: number) => {
  page.value = val
  getKeys()
}

const handleNextClick = (val: number) => {
  page.value = val
  getKeys()
}

const handlePrevClick = (val: number) => {
  page.value = val
  getKeys()
}

onMounted(() => {
  getKeys()
})
</script>

<style scoped>

</style>